
package com.patchmanage.back.controller;

import cn.hutool.core.io.FileUtil;
import com.aliyun.oss.ClientException;
import com.patchmanage.back.entity.FileLibrary;
import com.patchmanage.back.result.CodeMsg;
import com.patchmanage.back.result.Result;
import com.patchmanage.back.service.IFileLibraryService;
import com.patchmanage.back.utils.UUIDUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

@Api(value="文件 controller",tags={"文件"})
@RestController
@RequestMapping("file")
public class FileController {

    Logger logger = LoggerFactory.getLogger(FileController.class);

    @Autowired
    public IFileLibraryService fileLibraryService;

    //处理文件上传
    @ApiOperation(value = "上传文件", notes = "上传文件")
    @RequestMapping(value="uploadFile", method = RequestMethod.POST)
    @ResponseBody
    public Object uploadSpeechFile(@RequestParam("file") MultipartFile file) throws IOException, ClientException {

        Map<String,Object> map = new HashMap<>();
        if(file != null){
            String filename = file.getOriginalFilename();

            int location = filename.indexOf(".");
            String caselsh = "";
            if(location != -1){
                caselsh = filename.substring(filename.indexOf("."),filename.length());
            }

            String returnFileName = UUIDUtil.uuid() +  caselsh;
            String filePath = "/usr/local/patch-manage-back/file/"+ returnFileName;
            File f = FileUtil.writeFromStream(file.getInputStream(),filePath);

            map.put("fileName",returnFileName);
            map.put("size",file.getSize());
            map.put("filePath",filePath);
        }
        return map;
    }

    @GetMapping("/download")
    public Result<Object> downloadFile(HttpServletRequest request, HttpServletResponse response,@RequestParam("fileId") String fileId) {
        FileLibrary fb = fileLibraryService.getById(fileId);
        if (fb != null) {
            //设置文件路径
            File file = new File(fb.getFileUrl());
            if (file.exists()) {
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition", "attachment;fileName=" + fb.getSourceFileName());// 设置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    Result.success("下载成功");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return Result.error(CodeMsg.SERVER_ERROR);
    }
}

